package com.ndp.fb.walle.business.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.ndp.fb.rdb.model.EntrustAccountExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ndp.fb.enums.customaudience.CustomAudienceDataSourceType;
import com.ndp.fb.enums.customaudience.CustomAudienceSubType;
import com.ndp.fb.fbagent.service.CustomaudiencesFbServices;
import com.ndp.fb.rdb.api.CustomAudienceRdbService;
import com.ndp.fb.rdb.api.CustomAudienceTemplateRdbService;
import com.ndp.fb.rdb.api.EntrustAccountRdbService;
import com.ndp.fb.rdb.api.FbUserRdbService;
import com.ndp.fb.rdb.api.PageRdbService;
import com.ndp.fb.rdb.model.EntrustAccount;
import com.ndp.fb.rdb.model.Page;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.customaudience.CustomAudienceItem;
import com.ndp.fb.rdb.model.customaudience.CustomAudienceTemplate;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.business.LooklikeAudienceTmplService;
import com.ndp.fb.walle.model.vo.customaudience.param.CountryRatio;

/**
 * @Author: Evan on 1/6/2016  12:06.
 * Email: evan.wan@ndpmedia.com
 */
@Component
public class LooklikeAudienceTmplServiceImpl implements LooklikeAudienceTmplService {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Reference
    private CustomAudienceTemplateRdbService customAudienceTemplateRdbService;

    @Reference
    private CustomAudienceRdbService customAudienceRdbService;

    @Reference
    CustomaudiencesFbServices customaudiencesFbServices;

    @Reference
    private FbUserRdbService fbUserRdbService;

    @Reference
    PageRdbService pageRdbService;

    @Reference
    EntrustAccountRdbService entrustAccountRdbService;
    @Override
    public void createLookALikeByPage(Long pageId, List<CountryRatio> countryRatioList, User user) {

        Page page = pageRdbService.getPageByPageId(pageId);
        Long orgId = user.getOrgId();
        List<EntrustAccount> entrustAccounts = entrustAccountRdbService.getPagesByUserId(pageId, orgId);
        if (page != null ) {

            List<EntrustAccountExt> needUploadResource = entrustAccountRdbService.findAdAccountListByUserId(user.getTicket());
            Set<Long> hasPa = new HashSet<>();
            for (EntrustAccount entrustAccount : needUploadResource) {
                hasPa.add(entrustAccount.getFbAccountId());
            }

            for (CountryRatio countryRatio : countryRatioList) {
                String country = countryRatio.getCountry();
                String ratio = countryRatio.getRatio();
                String AudienceLookalikeName = "Lookalike (" + country + ", " + ratio + "%) -  People who like " + page.getName();
                CustomAudienceTemplate customAudienceTemplate = new CustomAudienceTemplate();
                customAudienceTemplate.setDataSourceType(CustomAudienceDataSourceType.SEED_BASED.getType());
                customAudienceTemplate.setDataSourceSubtype("PAGE_FANS");
                customAudienceTemplate.setApproximateCount(0l);
                customAudienceTemplate.setIsDelete(0);
                customAudienceTemplate.setScale("0");
                customAudienceTemplate.setDescription("");
                customAudienceTemplate.setTimeUpdated(System.currentTimeMillis());
                customAudienceTemplate.setTimeCreated(System.currentTimeMillis());
                customAudienceTemplate.setTimeContentUpdated(System.currentTimeMillis());
                customAudienceTemplate.setName(AudienceLookalikeName);
                customAudienceTemplate.setRetentionDays(180);
                customAudienceTemplate.setUserId(user.getTicket());
                customAudienceTemplate.setSubtype(CustomAudienceSubType.LOOKALIKE.getType());
                customAudienceTemplate.setOriginType("page");
                customAudienceTemplate.setOriginId(pageId);
                customAudienceTemplate.setCustomRatio(Integer.valueOf(ratio));
                Long customAudienceTemplateId = customAudienceTemplateRdbService.save(customAudienceTemplate);

                for (EntrustAccount entrustAccount : entrustAccounts) {
                    Long fbAccountId = entrustAccount.getFbAccountId();
                    if (hasPa.contains(fbAccountId)){
                        String fbAccountName = entrustAccount.getName();
                        saveCustomAudienceAndSendFbByPage(pageId, country, ratio, AudienceLookalikeName, customAudienceTemplateId, fbAccountId, fbAccountName, user.getTicket());
                    }
                }
            }
        }
    }

    private void saveCustomAudienceAndSendFbByPage(Long pageId, String country, String ratio, String audienceLookalikeName, Long customAudienceTemplateId, Long fbAccountId, String fbAccountName, String userId) {
        String token = fbUserRdbService.getTokenByUserId(userId);
        if (StringUtil.isNotEmpty(token)) {
            CustomAudienceItem customAudience = new CustomAudienceItem();
            customAudience.setCustomAudienceId(-1l);
            customAudience.setRequestQueueStatus(0);
            customAudience.setDeliveryStatusCode(-1);
            customAudience.setOperationStatusCode(-1);
            customAudience.setRequestQueueStatus(0);
            customAudience.setFbAccountId(fbAccountId);
            customAudience.setFbAccountName(fbAccountName);
            customAudience.setCustomAudienceTemplateId(customAudienceTemplateId);
            customAudience.setDeliveryStatusDescription("");
            customAudience.setTimeCreated(System.currentTimeMillis());
            customAudience.setTimeUpdated(System.currentTimeMillis());
            customAudience.setOperationStatusDescription("");
            customAudience.setVersion(System.currentTimeMillis() + "");
            customAudience.setOriginAudienceId(pageId);
            Long customAudienceDbId = customAudienceRdbService.saveCustomAudience(customAudience);

            customaudiencesFbServices.createCustomAudienceLookalikeByPage(pageId, country, ratio, audienceLookalikeName, fbAccountId, token, customAudienceDbId);
        }
    }


    @Override
    public void createLookALikeByAudience(Long templateId, List<CountryRatio> countryRatioList, User user) {
        CustomAudienceTemplate byId = customAudienceTemplateRdbService.findById(templateId + "");
        List<CustomAudienceItem> customAudienceItemList = customAudienceRdbService.findByTemplateId(templateId);

        if (byId != null && customAudienceItemList.size() > 0) {

            List<EntrustAccountExt> needUploadResource = entrustAccountRdbService.findAdAccountListByUserId(user.getTicket());
            Set<Long> hasPa = new HashSet<>();
            for (EntrustAccount entrustAccount : needUploadResource) {
                hasPa.add(entrustAccount.getFbAccountId());
            }

            for (CountryRatio countryRatio : countryRatioList) {
                String country = countryRatio.getCountry();
                String ratio = countryRatio.getRatio();
                String AudienceLookalikeName = "Lookalike (" + country + ", " + ratio + "%) - " + byId.getName();
                Long customAudienceTemplateId = saveCustomAudienceTemplate(templateId, AudienceLookalikeName, user, byId, countryRatio);

                for (CustomAudienceItem customAudienceItem : customAudienceItemList) {
                    Long fbAccountId = customAudienceItem.getFbAccountId();
                    if(hasPa.contains(fbAccountId)){ //判断此时 这个账号还有没有权限
                        saveCustomAudienceAndSendFb(AudienceLookalikeName, customAudienceTemplateId, customAudienceItem, countryRatio, user.getTicket());
                    } else {
                        logger.error("fbaccount>>>"+fbAccountId+";已经被解绑，不能创建相似受众!");
                    }
                }
            }
        }
    }

    private void saveCustomAudienceAndSendFb(String AudienceLookalikeName, Long customAudienceTemplateId, CustomAudienceItem customAudienceItem,
                                             CountryRatio countryRatio, String userId) {
        Long fbAccountId = customAudienceItem.getFbAccountId();
        Long customAudienceId = customAudienceItem.getCustomAudienceId();
        String fbAccountName = customAudienceItem.getFbAccountName();
        Integer deliveryStatusCode = customAudienceItem.getDeliveryStatusCode();
        Integer operationStatusCode = customAudienceItem.getOperationStatusCode();

        String token = fbUserRdbService.getTokenByUserId(userId);
        if (StringUtil.isNotEmpty(token) && 200 == deliveryStatusCode && 200 == operationStatusCode) {
            CustomAudienceItem customAudience = new CustomAudienceItem();
            customAudience.setCustomAudienceId(-1l);
            customAudience.setRequestQueueStatus(0);
            customAudience.setDeliveryStatusCode(-1);
            customAudience.setOperationStatusCode(-1);
            customAudience.setFbAccountId(fbAccountId);
            customAudience.setFbAccountName(fbAccountName);
            customAudience.setCustomAudienceTemplateId(customAudienceTemplateId);
            customAudience.setDeliveryStatusDescription("");
            customAudience.setTimeCreated(System.currentTimeMillis());
            customAudience.setTimeUpdated(System.currentTimeMillis());
            customAudience.setOperationStatusDescription("");
            customAudience.setVersion(System.currentTimeMillis() + "");
            customAudience.setOriginAudienceId(customAudienceItem.getCustomAudienceId());
            Long customAudienceDbId = customAudienceRdbService.saveCustomAudience(customAudience);
            customaudiencesFbServices.createCustomAudienceLookalike(AudienceLookalikeName, countryRatio.getCountry(),countryRatio.getRatio(), fbAccountId, customAudienceId, customAudienceDbId, token);
        } else {
            logger.info("自定义受众没有成功不能创建相似受众");
        }
    }

    private Long saveCustomAudienceTemplate(Long templateId, String name, User user, CustomAudienceTemplate byId, CountryRatio countryRatio) {
        CustomAudienceTemplate save = new CustomAudienceTemplate();
        BeanUtils.copyProperties(byId,save);
        save.setDataSourceType(CustomAudienceDataSourceType.SEED_BASED.getType());
        save.setImportedType("");
        save.setSubtype("");
        save.setDataSourceSubtype("CUSTOM_AUDIENCE_USERS");
        save.setApproximateCount(0l);
        save.setIsDelete(0);
        save.setScale("0");
        save.setDescription("");
        save.setTimeUpdated(System.currentTimeMillis());
        save.setTimeCreated(System.currentTimeMillis());
        save.setTimeContentUpdated(System.currentTimeMillis());
        save.setName(name);
        save.setRetentionDays(180);
        save.setUserId(user.getTicket());
        save.setSubtype(CustomAudienceSubType.LOOKALIKE.getType());
        save.setOriginType("custom_audience");
        save.setOriginId(templateId);
        save.setCountryCode(countryRatio.getCountry());
        save.setCustomRatio(Integer.valueOf(countryRatio.getRatio()));
        return customAudienceTemplateRdbService.save(save);
    }

    @Override
    public CustomAudienceTemplate findCustomAudienceTemplateByoriginIdAndcountryCodeAndratio(Long originId, String countryCode, String ratio) {
        return customAudienceTemplateRdbService.findCustomAudienceTemplateByoriginIdAndcountryCodeAndratio(originId, countryCode, ratio);
    }
}
